import React, { Component } from "react";
import { connect } from "react-redux";
import { nanoid } from "nanoid";

import { createAddPerson } from "../../redux/actions/person";

class Person extends Component {
    addPerson = () => {
        const name = this.nameNode.value;
        const age = parseInt(this.ageNode.value);

        const person = { id: nanoid(), name: name, age: age };

        this.props.addPerson(person);

        this.nameNode.value = "";
        this.ageNode.value = "";
    };

    render() {
        const { people, count } = this.props;

        return (
            <div>
                <h2>Person组件，上方组件和为：{count}</h2>
                <input
                    ref={(c) => (this.nameNode = c)}
                    type="text"
                    placeholder="请输入名字"
                />
                <input
                    ref={(c) => (this.ageNode = c)}
                    type="number"
                    placeholder="请输入年龄"
                />
                <button onClick={this.addPerson}>添加</button>
                <ul>
                    {people.map((p) => {
                        return (
                            <li key={p.id}>
                                {p.name} --- {p.age}
                            </li>
                        );
                    })}
                </ul>
            </div>
        );
    }
}

const mapStateToProps = (state) => ({
    people: state.people,
    count: state.count,
});
const mapDispatchToProps = {
    addPerson: createAddPerson,
};

export default connect(mapStateToProps, mapDispatchToProps)(Person);
